package com.ktkj.init.exception;

import com.ktkj.init.entity.UserInfo;
import com.ktkj.init.response.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.lang.reflect.UndeclaredThrowableException;


/**
 * The type Global exception handler.
 *
 * @author :yanlixiong
 * @date :2021-07-28 18:28:06
 */
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    @ExceptionHandler
    @ResponseBody
    public Response processException(Exception e) {
        int code = BusinessException.BUSSINESS_EXCEPTION;
        BindingResult bindingResult = null;
        String result = "";
        if (e instanceof BindException) {
            BindException ex = (BindException) e;
            bindingResult = ex.getBindingResult();
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            UserInfo userInfo = (UserInfo) SecurityUtils.getSubject().getPrincipal();
            if (userInfo == null) {
                code = BusinessException.NOT_LOGIN;
                result = "请先登录！";
            } else {
                HttpRequestMethodNotSupportedException ex = (HttpRequestMethodNotSupportedException) e;
                result = "无权限！";
            }
        } else if (e instanceof UnauthorizedException) {
            UnauthorizedException ex = (UnauthorizedException) e;
            code = BusinessException.NOT_ACCESS;
            result = ex.getMessage();
        } else if (e instanceof UndeclaredThrowableException) {
            Throwable undeclaredThrowable = ((UndeclaredThrowableException) e).getUndeclaredThrowable();
            result = undeclaredThrowable.getMessage();
        }
        if (bindingResult != null && !CollectionUtils.isEmpty(bindingResult.getFieldErrors())) {
            StringBuilder message = new StringBuilder();
            for (FieldError error : bindingResult.getFieldErrors()) {
                String msg = error.getDefaultMessage();
                message.append(msg).append(" ");
            }
            result = message.toString();
            result = result.substring(0, result.length() - 1);
        }
        return Response.error(code, result);
    }


}
